package cn.org.xiaosheng.JUC;

import java.util.concurrent.PriorityBlockingQueue;

/**
 * @author XiaoSheng
 * @date 2024/8/27 下午1:05
 */
public class PriorityBlockingQueueTest {
    private final PriorityBlockingQueue<Task> tasks = new PriorityBlockingQueue<>();

    public void schedule(Task task) {
        tasks.offer(task);
    }

    public void runNextTask() throws InterruptedException {
        Task nextTask = tasks.take();
        if (nextTask != null) {
            nextTask.run();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        PriorityBlockingQueueTest scheduler = new PriorityBlockingQueueTest();
        scheduler.schedule(new Task("High Priority Task", 1));
        scheduler.schedule(new Task("Low Priority Task", 10));

        scheduler.runNextTask();  // 应该先执行 High Priority Task
    }
}

class Task implements Comparable<Task> {
    private String name;
    private int priority;

    public Task(String name, int priority) {
        this.name = name;
        this.priority = priority;
    }

    @Override
    public int compareTo(Task other) {
        return Integer.compare(this.priority, other.priority);
    }

    public void run() {
        System.out.println("Running task: " + name);
    }
}
